package rolelogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetRoleRuleByRidLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetRoleRuleByRidLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRoleRuleByRidLogic {
	return &GetRoleRuleByRidLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetRoleRuleByRidLogic) GetRoleRuleByRid(in *syspb.GetRoleRuleByRidReq) (*syspb.GetRoleRuleByRidResp, error) {
	if in.GetId() == 0 {
		return &syspb.GetRoleRuleByRidResp{RuleIds: nil}, nil
	}

	enforcer := l.svcCtx.AdapterCasbin.SetCtxSession(l.ctx, nil).Enforcer
	gp := enforcer.GetFilteredNamedPolicy("p", 0, convertor.ToString(in.GetId()))

	var dataList []int64
	for _, v := range gp {
		val, _ := convertor.ToInt(v[1])
		dataList = append(dataList, val)
	}

	return &syspb.GetRoleRuleByRidResp{RuleIds: dataList}, nil
}
